package com.example.dynamicschedule.utils;

import com.alibaba.fastjson.JSON;
import com.example.dynamicschedule.bean.CkOrderAchievementForm;
import com.example.dynamicschedule.bean.CkOrderRecoveryData;
import com.example.dynamicschedule.bean.CkStopNoticePerson;
import com.example.dynamicschedule.bean.CkStopNoticePersonTimes;
import com.example.dynamicschedule.dao.CkStopNoticePersonTimesMapper;
import com.example.dynamicschedule.redis.RedisService;
import com.example.dynamicschedule.service.CkFeedBackService;
import com.example.dynamicschedule.service.CkOrderAchievementFormService;
import com.example.dynamicschedule.service.CkStopNoticePersonService;
import com.example.dynamicschedule.service.PeopleCallService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class NoAnswerAndMissPeopleUtils {
    @Autowired
    private RedisService redisService;
    @Autowired
    private CkStopNoticePersonService ckStopNoticePersonService;
    @Autowired
    private CkFeedBackService ckFeedBackService;
    @Autowired
    private CkOrderAchievementFormService ckOrderAchievementFormService;
    @Autowired
    private CkStopNoticePersonTimesMapper ckStopNoticePersonTimesMapper;
    protected static final Logger logger = LoggerFactory.getLogger(PeopleCallService.class);
    /**
     * 未接三次变为失联
     *
     * @param ckOrderRecoveryDataList
     * @param noAnswer
     * @param missCkStopNoticePeople
     * @return
     */
    public List<CkStopNoticePerson> noAnswerThree(List<CkOrderRecoveryData> ckOrderRecoveryDataList,
                                                  String noAnswer,
                                                  List<CkStopNoticePerson> missCkStopNoticePeople,
                                                  CkStopNoticePersonTimes ckStopNoticePersonTimes) {
        Map<String, Integer> noAnswerPeopleMap = null;
       //CkStopNoticePersonTimes ckStopNoticePersonTimes= ckStopNoticePersonTimesMapper.selectByKey("noAnswerPeople");
        if (ckStopNoticePersonTimes!=null) {
            String value = ckStopNoticePersonTimes.getMapValue();
           // Map<Object, Object> noAnswerPeople = redisService.hmget("noAnswerPeople");
            noAnswerPeopleMap = JSON.parseObject(value, Map.class);
        } else {
            noAnswerPeopleMap = new HashMap<>();
        }
        for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDataList) {
            String feedbackCode = ckOrderRecoveryData.getFeedbackCode();
            if (noAnswer.contains(feedbackCode)) {
                String serialNumber = ckOrderRecoveryData.getSerialNumber();
                if (noAnswerPeopleMap.get(serialNumber) == null) {
                    noAnswerPeopleMap.put(serialNumber, 1);
                } else {
                    Integer integer = noAnswerPeopleMap.get(serialNumber);
                    integer += 1;
                    if (integer == 3) {
                        CkStopNoticePerson ckStopNoticePerson = new CkStopNoticePerson();
                        BeanUtils.copyProperties(ckOrderRecoveryData, ckStopNoticePerson);
                        ckStopNoticePerson.setType((byte) 2);
                        ckStopNoticePerson.setDivisionMode((byte) 1);
                        ckStopNoticePerson.setIsDelete((byte) 0);
                        missCkStopNoticePeople.add(ckStopNoticePerson);
                        noAnswerPeopleMap.remove(serialNumber);
                    } else {
                        noAnswerPeopleMap.put(serialNumber, integer);
                    }
                }
            }
        }
        if (ckStopNoticePersonTimes.getMapKey()==null) {
            ckStopNoticePersonTimes=new CkStopNoticePersonTimes();
            ckStopNoticePersonTimes.setMapKey("noAnswerPeople");
            ckStopNoticePersonTimes.setMapValue(JSON.toJSONString(noAnswerPeopleMap));
            ckStopNoticePersonTimesMapper.insert(ckStopNoticePersonTimes);
        } else {
            ckStopNoticePersonTimes.setMapValue(JSON.toJSONString(noAnswerPeopleMap));
            ckStopNoticePersonTimesMapper.updateByPrimaryKeyWithBLOBs(ckStopNoticePersonTimes);
        }
       // redisService.hmset("noAnswerPeople", noAnswerPeopleMap);
        return missCkStopNoticePeople;
    }

    /**
     * 失联三次变为停催
     *
     * @param missCkStopNoticePeople
     * @return
     */
    public List<CkStopNoticePerson> missPeopleThree(List<CkStopNoticePerson> missCkStopNoticePeople) {
        List<CkStopNoticePerson> threes = new ArrayList<>();
        Map<String, Object> missPeopleMap = null;
        CkStopNoticePersonTimes ckStopNoticePersonTimes= ckStopNoticePersonTimesMapper.selectByKey("missPeople");
        if (ckStopNoticePersonTimes!=null) {
            String value = ckStopNoticePersonTimes.getMapValue();
           // Map<Object, Object> missPeople = redisService.hmget("missPeople");
            missPeopleMap = JSON.parseObject(value, Map.class);
        } else {
            missPeopleMap = new HashMap<>();
        }
        Iterator<CkStopNoticePerson> iterator = missCkStopNoticePeople.iterator();
        while (iterator.hasNext()) {
            CkStopNoticePerson next = iterator.next();
            String serialNumber = next.getSerialNumber();
            if (missPeopleMap.get(serialNumber) == null) {
                missPeopleMap.put(serialNumber, 1);
            } else {
                Integer integer = Integer.valueOf(String.valueOf(missPeopleMap.get(serialNumber)));
                integer += 1;
                if (integer == 3) {
                    next.setType((byte) 1);
                    threes.add(next);
                    iterator.remove();
                    missPeopleMap.put(serialNumber, 0);
                } else {
                    missPeopleMap.put(serialNumber, integer);
                }
            }
        }
        if (ckStopNoticePersonTimes == null) {
            ckStopNoticePersonTimes=new CkStopNoticePersonTimes();
            ckStopNoticePersonTimes.setMapKey("missPeople");
            ckStopNoticePersonTimes.setMapValue(JSON.toJSONString(missPeopleMap));
            ckStopNoticePersonTimesMapper.insert(ckStopNoticePersonTimes);
        } else {
            ckStopNoticePersonTimes.setMapValue(JSON.toJSONString(missPeopleMap));
            ckStopNoticePersonTimesMapper.updateByPrimaryKeyWithBLOBs(ckStopNoticePersonTimes);
        }
       // redisService.hmset("missPeople", missPeopleMap);
        return threes;
    }

    /**
     * 判断失联表中是否出现成功联系
     * @param ckOrderRecoveryDataList
     * @param stopNumbers
     * @param missNumbers
     * @return
     */
    public List<CkStopNoticePerson> answerPeople(List<CkOrderRecoveryData> ckOrderRecoveryDataList, String stopNumbers, String missNumbers) {
        logger.info("查询所有失联单并对失联单分类开始");
        //不重复的已失联案件号
        Set<String> serialNumberList = new HashSet<>();
        //map中存储案件所对应的所有bean
        Map<String, List<CkStopNoticePerson>> ckStopNoticePeopleMap = new HashMap<>();
        //案件号所对应的list
        List<CkStopNoticePerson> ckStopNoticePeopleList = ckStopNoticePersonService.findOutOfContactAll();
        for (CkStopNoticePerson ckStopNoticePerson : ckStopNoticePeopleList) {
            String serialNumber = ckStopNoticePerson.getSerialNumber();
            serialNumberList.add(serialNumber);
            List<CkStopNoticePerson> ckStopNoticePeoples=null;
            if (ckStopNoticePeopleMap.get(serialNumber) == null) {
                ckStopNoticePeoples = new ArrayList<>();
            } else {
                ckStopNoticePeoples=ckStopNoticePeopleMap.get(serialNumber);
            }
            ckStopNoticePeoples.add(ckStopNoticePerson);
            ckStopNoticePeopleMap.put(serialNumber,ckStopNoticePeoples);
        }
        logger.info("查询所有失联单并对失联单分类结束");

        //存储失联状态重新获取到不失联list,在已失联表中删除
        String answer = ckFeedBackService.selectByChinese("已接通");
        List<CkStopNoticePerson> contactCkStopNoticePeople = new ArrayList<>();
        for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDataList) {
            String serialNumber = ckOrderRecoveryData.getSerialNumber();
            if (serialNumberList.contains(serialNumber)) {
                String feedbackCode = ckOrderRecoveryData.getFeedbackCode();
                if (!stopNumbers.contains(feedbackCode)&&!missNumbers.contains(feedbackCode)) {
                    if (answer.equalsIgnoreCase(feedbackCode)) {
                        List<CkStopNoticePerson> ckStopNoticePeople = ckStopNoticePeopleMap.get(serialNumber);
                        ckStopNoticePeople.stream().forEach(ckStopNoticePerson -> {
                            ckStopNoticePerson.setIsDelete((byte)1);
                        });
                        contactCkStopNoticePeople.addAll(ckStopNoticePeople);
                    }
                }
            }
        }
        return contactCkStopNoticePeople;
    }

    /**
     * 催收成绩表
     * @param ckOrderRecoveryDataList
     * @return
     */
    public   Map<String, List<CkOrderAchievementForm>> getAchievementForm(List<CkOrderRecoveryData> ckOrderRecoveryDataList) {
        Map<String, CkOrderAchievementForm> ckOrderRecoveryDataMap = ckOrderAchievementFormService.selectAll();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        //新增成绩表
        List<CkOrderAchievementForm> addCkOrderAchievementForm = new ArrayList<>();
        //更新成绩表
        List<CkOrderAchievementForm> updateCkOrderAchievementForm = new ArrayList<>();
        for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDataList) {
            String customerId = ckOrderRecoveryData.getCustomerId();
            Double overdueAmount = ckOrderRecoveryData.getOverdueAmount();
            if (ckOrderRecoveryDataMap.get(customerId) == null) {
                CkOrderAchievementForm ckOrderAchievementForm = new CkOrderAchievementForm();
                ckOrderAchievementForm.setCollectorId(customerId);
                String customerServiceName = ckOrderRecoveryData.getCustomerServiceName();
                ckOrderAchievementForm.setCollectorName(customerServiceName);
                ckOrderAchievementForm.setAmountRecovered("0");
                ckOrderAchievementForm.setDate(format);
                ckOrderAchievementForm.setNumberOfCasesHandled(1);
                ckOrderAchievementForm.setAmountOverdue(String.valueOf(overdueAmount));
                ckOrderAchievementForm.setRateRecovered("0");
                ckOrderRecoveryDataMap.put(customerId,ckOrderAchievementForm);
                addCkOrderAchievementForm.add(ckOrderAchievementForm);
            } else {
                CkOrderAchievementForm ckOrderAchievementForm = ckOrderRecoveryDataMap.get(customerId);
                Integer numberOfCasesHandled = ckOrderAchievementForm.getNumberOfCasesHandled();
                numberOfCasesHandled+=1;
                String amountOverdue = ckOrderAchievementForm.getAmountOverdue();
                amountOverdue = new BigDecimal(amountOverdue).add(new BigDecimal(overdueAmount)).toString();
                ckOrderAchievementForm.setAmountOverdue(amountOverdue);
                String amountRecovered = ckOrderAchievementForm.getAmountRecovered();
                String s = new BigDecimal(amountRecovered).divide(new BigDecimal(amountOverdue), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).toString();
                ckOrderAchievementForm.setRateRecovered(s);
                ckOrderAchievementForm.setNumberOfCasesHandled(numberOfCasesHandled);
                ckOrderRecoveryDataMap.put(customerId,ckOrderAchievementForm);
                updateCkOrderAchievementForm.add(ckOrderAchievementForm);
            }
        }
        Map<String, List<CkOrderAchievementForm>> resultMap = new HashMap<>();
        resultMap.put("add",addCkOrderAchievementForm);
        resultMap.put("update",updateCkOrderAchievementForm);
        return resultMap;
    }
}
